package com.ztx.service.user.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import com.ztx.model.ResourceRole;
import com.ztx.model.ResourceVO;
import com.ztx.model.RoleVO;
import com.ztx.pagemodel.easyui.Tree;
import com.ztx.service.user.IRoleService;
import com.ztx.utils.Utils;

@Repository
public class RoleServiceImpl implements IRoleService {

	@Resource
	private SqlSessionTemplate sqlSessionTemplate = null;

	@Override
	public List<Tree> queryResourceByRoleId(String roleId) {
		// 查询所有资源
		List<ResourceVO> allResource = sqlSessionTemplate
				.selectList(ResourceVO.class.getName() + ".getAllResource");

		// 根据roleId查询资源
		List<ResourceVO> resourceByRoleid = sqlSessionTemplate.selectList(
				ResourceVO.class.getName() + ".getResourceByRoleid", roleId);
		Set<String> checkedResourceSet = new HashSet<>();
		for (ResourceVO rc : resourceByRoleid) {
			checkedResourceSet.add(rc.getId());
		}
		List<Tree> listTree = new ArrayList<>();
		for (ResourceVO ar : allResource) {
			Tree tree = new Tree();
			BeanUtils.copyProperties(ar, tree);
			tree.setText(ar.getName());
			if (checkedResourceSet.contains(ar.getId())) {
				tree.setChecked(true);
			}
			listTree.add(tree);
		}

		return listTree;
	}

	@Override
	public void addResourceRole(String roleId, String[] resIds)
			throws Exception {
		// 先删除再增加
		sqlSessionTemplate.delete(RoleVO.class.getName()
				+ ".delResourceRoleByRoleId", roleId);
		for (String resId : resIds) {
			ResourceRole rr = new ResourceRole();
			rr.setId(Utils.createId());
			rr.setRoleId(roleId);
			rr.setResourceId(resId);
			sqlSessionTemplate.insert(RoleVO.class.getName()
					+ ".addResourceRole", rr);
		}

	}

}
